from peewee import *
from app.model.baseModel.MysqlBaseModel import MysqlBaseModel
from app.model.baseModel.MysqlBaseModel import mysql_db
from functools import wraps


class User(MysqlBaseModel):  # 类的小写即表名
    username = CharField()  # 字段声明
    email = CharField()
    id = BigIntegerField()

if __name__ == '__main__':


    def logit(func):
        @wraps(func)
        def with_logging(*args, **kwargs):
            print(func.__name__ + " was called")
            return func(*args, **kwargs)

        return with_logging


    @logit
    def addition_func(x):
        """Do some math."""
        return x + x


    result = addition_func(4)
    # Output: addition_func was called
    print(result)
    # data = User.select().where(User.username == 'Grandma L.')
    # print(data.get())
    # 使用create创建数据 返回Model
    # userModel = User.create(username='Charlie', email="66@qq.com")
    # print(userModel, userModel.username)

    # 使用save创建数据 同时获取model对象
    # userModel = User(username="Dale", email="dale@outlook.com")
    # res = userModel.save()
    # print(userModel, res, userModel.username)

    # 使用insert 只插入,不生成model,返回数据主键id
    # userId = User.insert(username='Mickey', email="mickey@163.com").execute()
    # print(userId)

    # 批量插入,返回插入数据条数
    # data_source = [
    #     {'username': 'jax', 'email': 'jax@gmail.com'},
    #     {'username': 'ken', 'email': 'ken@Dingtalk.com'},
    # ]
    #
    # num = User.insert_many(data_source).execute()
    # print(num)

    # 启用事务,循环批量插入数据
    # data_source = [
    #     {'username': 'jax', 'email': 'jax@gmail.com'},
    #     {'username': 'ken', 'email': 'ken@Dingtalk.com'},
    #     {'username': 'test1', 'email': 'test1@Dingtalk.com'},
    #     {'username': 'test2', 'email': 'test2@Dingtalk.com'},
    #     {'username': 'test1', 'email': 'test3@Dingtalk.com'},
    # ]
    #
    # with mysql_db.atomic():
    #     for idx in range(0, len(data_source), 2):
    #         User.insert_many(data_source[idx:idx + 2]).execute()
    #
    # with mysql_db.atomic():
    #     for idx in chunked(data_source, 2):
    #         User.insert_many(data_source[idx:idx + 2]).execute()

    # 使用model对象批量存储数据
    # users = [User(username=line['username'],email=line['email']) for line in data_source]
    # with mysql_db.atomic():
    #     User.bulk_create(users, batch_size=2)

    # 批量更新对象
    # u1, u2, u3 = [User.create(username='u%s' % i) for i in (1, 2, 3)]
    #
    # # Now we'll modify the user instances.
    # u1.username = 'u1-x'
    # u2.username = 'u2-y'
    # u3.username = 'u3-z'
    #
    # # Update all three users with a single UPDATE query.
    # User.bulk_update([u1, u2, u3], fields=[User.username])
    #
    #  分批提交事务
    # for row in mysql_db.batch_commit(data_source, 2):
    #     print(row)

    # 指定条件更新数据
    # query = User.update(username='ajax').where(User.id==45)
    # print(query.execute())
